package com.teng.exceltest.controller;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.teng.exceltest.util.Excel2ImageUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class ExcelController {

    @GetMapping("/test")
    public void test(HttpServletResponse response) throws IOException, InvalidFormatException {
        ServletOutputStream outputStream = null;
        BufferedImage image = Excel2ImageUtil.getImage();
        // *This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams. */


        try {
            outputStream = (ServletOutputStream)response.getOutputStream();
            response.setHeader("Context-Type", "image/*");
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder( outputStream );
            encoder.encode( image ); //Encode a BufferedImage as a JPEG data stream.

            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
